import axios from 'axios';
import { Message } from 'element-ui';
import { Loading } from 'element-ui';
import store from '../store/index'
// 创建实例  如果前端采用代理模式跨域，这块省略
const instance = axios.create({
  baseURL: 'http://localhost:7001/',
  timeout: 3000
})
// 拦截请求
instance.interceptors.request.use((config) => {
  // loading 开启 
  // token
  // config.headers.authorization = sessionStorage.getItem('token')
  config.headers.authorization = store.state.token
  // console.log(config, 'config')
  return config;
}, (e) => {
  return Promise.reject(e)
})

// 拦截响应
instance.interceptors.response.use((response) => {
  if (response.data.code === 0) {
    // 关闭loading
    return response.data;
  } else {
    return response
  }
}, (err) => {

  let status = err.response.status
  // 判断状态码 404 500
  switch (status) {
    case 404:
      Message.error('not Found')
      break;
    case 500:
      Message.error('服务器内部报错')
      break;
    default:
      Message.error('其他错误')
  }
})

// 返回实例
export default instance;